package com.beta.resource.model;

import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;

import com.beta.resource.model.UserInfo;
import com.beta.resource.protocol.Mecha;
import com.beta.resource.utils.BaseString;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.oauth2.jwt.Jwt;

public class UserInfo {
    private static final String TOKEN_KEYWORD_USERNAME = "preferred_username";
    private static final String TOKEN_KEYWORD_EMAIL = "email";
    private int uid;
    private String suid;
    private String username;
    private String email;
    private String token;
    private String mechaToken;
    // private JwtAuthenticationToken mToken;
    private Logger log = LoggerFactory.getLogger(getClass());
    
    public UserInfo(JwtAuthenticationToken token){
        // mToken = token;
        analyzing(token);
    }
    
    public void copy(UserInfo info){
        uid = info.getUid();
        suid = info.getSuid();
        username = info.getUsername();
        email = info.getEmail();
        token = info.getToken();
    }

    private void analyzing(JwtAuthenticationToken token){
        Jwt credentials = (Jwt) token.getCredentials();
        setSuid(credentials.getSubject());
        setUsername((String) credentials.getClaims().get(TOKEN_KEYWORD_USERNAME));
        setEmail((String) credentials.getClaims().get(TOKEN_KEYWORD_EMAIL));
        setToken(credentials.getTokenValue());
    }    
    
    public String getToken(String querycode) {
        log.debug("getToken: "+ querycode +", "+mechaToken);
        if(querycode.equals(mechaToken)){
            return token;
        }
        return "";
    }

    public String createMechaToken(){
        mechaToken = BaseString.getRandomString(Mecha.TOKEN_LENGTH);
        return mechaToken;
    }

    public String getMechaToken(){
        return mechaToken;
    }

    public void setToken(String token) {
        this.token = token;
    }

    public String getToken(){
        return token;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public int getUid() {
        return uid;
    }
    public void setUid(int uid) {
        this.uid = uid;
    }
    public String getSuid() {
        return suid;
    }
    public void setSuid(String suid) {
        this.suid = suid;
    }
}
